package io.yuanqi.hgtcshop.controller.share;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.yuanqi.hgtcshop.controller.WeChatController;
import io.yuanqi.hgtcshop.entity.vo.ResultMessage;
import io.yuanqi.hgtcshop.utils.HttpGetUtil;
import io.yuanqi.hgtcshop.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
//@Api(tags = "买家端,分享接口")
@RequestMapping("/")
public class TestController {

    @Autowired
    private WxMpService wxMpService;

    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.secret}")
    private String secret;

    @Autowired
    private WeChatController weChatController;


    /**
     * 微信授权路由
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("state") String state,
                            @RequestParam("url") String url) {
        log.info(".authorize state:{} url:{}", state, url);
        //这个方法的三个参数分别是授权后的重定向url、获取用户信息类型和state
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(
                url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(state));
        log.info("【微信网页授权】获取code,redirectUrl={}", redirectUrl);
        return "redirect:" + redirectUrl;
    }


    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code, @RequestParam("state") String state) {
        log.info(".userInfo code:{} state:{}", code, state);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
        }
        //获取openId
        //String openId = wxMpOAuth2AccessToken.getOpenId();
        //获取accessToken
        //String accessToken = wxMpOAuth2AccessToken.getAccessToken();
        // 获取微信用户的公开信息
        WxMpUser user = null;
        try {
            user = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        } catch (Exception e) {
            log.info("【获取微信用户信息】获取微信用户信息失败,user={}", user);
        }
        log.info("user:{}", user);
        return user.getOpenId();
    }


    @RequestMapping(value = "/openIdMsg", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    @ResponseBody
    public void openIdMsg(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        log.info(".openIdMsg 接受到请求");
        String redirect_uri = URLEncoder.encode("https://buyer-api.hgtc.shop/buyerHgtc/WxOpenIdServlet", "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=" + redirect_uri +
                "&appid=" + appId + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        log.info(".openIdMsg url：{}", url);
        try {
            response.sendRedirect(url);
        } catch (Exception e) {
            log.error(".openIdMsg 转发异常", e);
        }
        log.info(".openIdMsg 处理完成");
    }

    @RequestMapping(value = "/WxOpenIdServlet", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    @ResponseBody
    public void WxOpenIdServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info(".WxOpenIdServlet 进来了");
        Map<String, Object> map = new HashMap<>();
        String code = request.getParameter("code");
        log.info(".WxOpenIdServlet code:{}", code);
        if (code == null) {
            log.error(".WxOpenIdServlet 获取code失败：{}", code);
        }

//        Map<String, Object> params = new HashMap<>();
//        params.put("secret", secret); // 公众号密钥
//        params.put("appid", appId);  // 公众号appid
//        params.put("grant_type", "authorization_code");
//        params.put("code", code);
//        String result = HttpGetUtil.httpRequestToString("https://api.weixin.qq.com/sns/oauth2/access_token", params);
//        log.info(".WxOpenIdServlet result:{}",result);
//        JSONObject jsonObject = JSONObject.fromObject(result);
//
//        String openid = jsonObject.getString("openid");
//        map.put("openId", openid);
//        log.info(".WxOpenIdServlet openId为：{}", openid);

        ResultMessage<JSONObject> wxInfoByCode = weChatController.getWxInfoByCode(code);
        log.info(".WxOpenIdServlet wxInfoByCode:{}", JSON.toJSONString(wxInfoByCode));
        if (wxInfoByCode.isSuccess()) {
            JSONObject jsonObject = wxInfoByCode.getResult();
            String openId = jsonObject.getString("openid");
            // https://ruyejiaren.com4.bc8t.cn/#/?token=5OXFR3IOPGFQO2UEQ0XNZF79
            response.sendRedirect("https://buyer-api.hgtc.shop/#/?token=" + openId);
        } else {
            log.error(".WxOpenIdServlet 调用getWxInfoByCode失败");
        }
//        return ResultUtil.data(openid);
    }


    public static String httpRequestToString(String url,
                                             Map<String, String> params) {
        String result = null;
        try {
            InputStream is = httpRequestToStream(url, params);
            BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            result = buffer.toString();
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    private static InputStream httpRequestToStream(String url,
                                                   Map<String, String> params) {
        InputStream is = null;
        try {
            String parameters = "";
            boolean hasParams = false;
            for (String key : params.keySet()) {
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key + "=" + value + "&";
                hasParams = true;
            }
            if (hasParams) {
                parameters = parameters.substring(0, parameters.length() - 1);
            }


            url += "?" + parameters;

            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setConnectTimeout(50000);
            conn.setReadTimeout(50000);
            conn.setDoInput(true);
            //设置请求方式，默认为GET
            conn.setRequestMethod("GET");


            is = conn.getInputStream();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }


}
